package com.haixiaoke.saas.common.utils;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @Author panda
 * @Date 2024/7/12
 **/
public class ExportUtil {


    public static String processHtml(String htmlString) {
        // 可以在这里进行 HTML 处理，如解析并转换为适合生成 Word 的格式
        // 这里简单地移除 <p> 标签
        return htmlString.replaceAll("<p>", "").replaceAll("</p>", "\n");
    }

    public static byte[] generateWordDocument(String plainText) throws IOException {
        plainText = processHtml(plainText);
        XWPFDocument document = new XWPFDocument();
        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun run = paragraph.createRun();

        String[] split = plainText.split("\n");
        for (String line : split) {
            //填充字符串
            run.setText(line);
            //换行
            run.addBreak();
        }

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        document.write(outputStream);
        document.close();

        return outputStream.toByteArray();
    }
}
